package com.hbun.cxcy.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hbun.cxcy.common.utils.PageUtils;
import com.hbun.cxcy.common.utils.R;

import com.hbun.cxcy.entity.Achievement;
import com.hbun.cxcy.entity.User;
import com.hbun.cxcy.service.UserService;
import com.hbun.cxcy.utils.JWTUtils;
import com.hbun.cxcy.vo.LoginVo;
import com.hbun.cxcy.vo.RegisterVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author mahaunyu
 * @since 2022-01-24
 */
@CrossOrigin
@RestController
@RequestMapping("/cxcy/admin")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    JavaMailSenderImpl mailSender;
    @Autowired
    StringRedisTemplate redisTemplate;

    @Value("${spring.mail.username}")
    String boss;

    @GetMapping("/email")
    public R getEmail(@RequestParam("email") String email) {
        // 检查邮箱是否合法
        email = email.trim(); // 去除空格，省去不必要的麻烦
        boolean isEmail = Validator.isEmail(email);
        if (!isEmail) {
            R.error("对不起！您的邮箱格式不正确！");
        }
        //  重复邮箱处理
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("email", email);
        List<User> userList = userService.list(wrapper);
        if (userList.size() != 0) {
            return R.error("对不起！该邮箱以被注册，请更换新的邮箱");
        }


        SimpleMailMessage message = new SimpleMailMessage();
        // 邮件标题
        message.setSubject("通知--MAC官网后台管理注册信息");
        // 内容

        //  放到Redis
        // 1.接口防刷
        String redisCode = redisTemplate.opsForValue().get("email:code" + email);
        if (!StringUtils.isEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                //60s内不能再发
                return R.error("验证码提交频率过高");
            }
        }
        // 生成随机六位数的组合
        String code = RandomUtil.randomNumbers(6) + "_" + System.currentTimeMillis();
        // 2.验证码的再次校验----存入redis
        // redis缓存验证码，五分钟有效，防止同一个手机号在60s内重复发送验证码
        redisTemplate.opsForValue().set("email:code" + email, code, 5, TimeUnit.MINUTES);
        message.setText(code.split("_")[0]);

        // 设置收信人和写信人
        message.setFrom(boss);
        message.setTo(email);
        // 邮件发送
        mailSender.send(message);
        Map<String, Object> map = new HashMap<>();
        map.put("email", email);
        map.put("expire", 5 * 60);
        return R.ok().put("msg", map);
    }

    @PostMapping("/register")
    public R register(@RequestBody RegisterVo register) {
        // 上面的邮箱注册已经判断完成是否是重复邮箱，所以这个不需要判断，重复用户名在前端校验
        System.out.println(register);
        int res = userService.register(register);
        if (res == 1) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @PostMapping("/login")
    public R login(@RequestBody LoginVo loginVo) {
        // 判断邮箱和密码是否正确
        String token = userService.login(loginVo);

        if (!StringUtils.isEmpty(token)) {
            return R.ok().setData(token);
        } else {
            return R.error("邮箱或密码错误");
        }
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("cxcyweb:achievements:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = userService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    //@RequiresPermissions("cxcy:user:info")
    public R info(@PathVariable("id") Long id) {
        User user = userService.getById(id);

        return R.ok().put("user", user);
    }


    /**
     * 修改
     */
    @RequestMapping("/update")
    //@RequiresPermissions("cxcy:user:update")
    public R update(@RequestBody User user) {
        userService.updateByIdWithCustom(user);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    //@RequiresPermissions("cxcy:user:delete")
    public R delete(@RequestBody Long[] ids) {
        // 逻辑删除
        userService.removeByIdsWithCustom(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 解析token
     */
    @RequestMapping("/user-find")
    public R Info(@RequestParam("token") String token) {
        if (!StringUtils.isEmpty(token)) {
            Claims claims = JWTUtils.checkJWT(token);
            if (claims == null) {
                // 说明登录过期
                return R.error("错误");
            }
            Integer id = (Integer) claims.get("id");
            String userName = (String) claims.get("userName");
            Map<String, Object> map = new HashMap<>();
            map.put("userName", userName);
            map.put("id", id);
            return R.ok().put("data", map);
        }
        return R.error("错误");
    }
}

